<template>
  <div class="config-history-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <el-icon><Document /></el-icon>
          <span style="margin-left: 8px;">配置历史</span>
          <el-button type="primary" @click="loadConfigHistory" :loading="loading" style="margin-left: auto;">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <!-- 设备选择 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="8">
          <el-select 
            v-model="selectedDevice" 
            placeholder="选择设备" 
            @change="onDeviceChange"
            style="width: 100%;"
          >
            <el-option
              v-for="device in devices"
              :key="device.id"
              :label="`${device.name} (${device.ip_address})`"
              :value="device.id"
            />
          </el-select>
        </el-col>
        <el-col :span="16">
          <el-input
            v-model="searchText"
            placeholder="搜索配置文件名或时间"
            clearable
            style="width: 100%;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
      </el-row>

      <!-- 配置历史列表 -->
      <el-table 
        :data="filteredConfigs" 
        v-loading="loading" 
        stripe
        @row-click="togglePreview"
        style="cursor: pointer;"
        :expand-row-keys="expandedRows"
        row-key="id"
      >
        <el-table-column type="expand" width="30">
          <template #default="{ row }">
            <div class="config-preview">
              <div class="preview-header">
                <el-icon><Document /></el-icon>
                <span style="margin-left: 8px; font-weight: 500;">配置预览 - {{ row.filename }}</span>
                <el-button 
                  type="primary" 
                  size="small" 
                  @click.stop="viewConfig(row)"
                  style="margin-left: auto;"
                >
                  <el-icon><View /></el-icon>
                  完整查看
                </el-button>
              </div>
              <div class="preview-content">
                <el-input
                  v-model="row.previewContent"
                  type="textarea"
                  :rows="15"
                  readonly
                  style="font-family: 'Courier New', monospace; font-size: 12px;"
                  :placeholder="row.previewLoading ? '正在加载...' : '点击加载配置内容'"
                  @click.stop="loadPreviewContent(row)"
                />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="filename" label="文件名" width="300" show-overflow-tooltip />
        <el-table-column label="备份时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.backup_time) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="大小" width="100">
          <template #default="{ row }">
            {{ formatSize(row.file_size) }}
          </template>
        </el-table-column>
        <el-table-column label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_manual ? 'warning' : 'info'" size="small">
              {{ row.is_manual ? '手动' : '自动' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click.stop="viewConfig(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button type="warning" size="small" @click.stop="selectForCompare(row)">
              <el-icon><Files /></el-icon>
              对比
            </el-button>
            <el-button type="danger" size="small" @click.stop="deleteConfig(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="totalConfigs"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; text-align: right;"
      />
    </el-card>

    <!-- 配置查看对话框 -->
    <el-dialog
      v-model="configDialogVisible"
      :title="`配置内容 - ${selectedConfig?.filename}`"
      width="90%"
      :before-close="handleConfigDialogClose"
    >
      <div v-if="selectedConfig" class="config-viewer">
        <el-descriptions :column="2" border style="margin-bottom: 20px;">
          <el-descriptions-item label="设备名称">{{ selectedConfig.device?.name }}</el-descriptions-item>
          <el-descriptions-item label="备份时间">{{ formatTime(selectedConfig.backup_time) }}</el-descriptions-item>
          <el-descriptions-item label="文件大小">{{ formatSize(selectedConfig.file_size) }}</el-descriptions-item>
          <el-descriptions-item label="备份类型">{{ selectedConfig.is_manual ? '手动' : '自动' }}</el-descriptions-item>
        </el-descriptions>

        <el-input
          v-model="configContent"
          type="textarea"
          :rows="25"
          readonly
          style="font-family: 'Courier New', monospace; font-size: 12px;"
          placeholder="正在加载配置内容..."
        />
      </div>
    </el-dialog>

    <!-- 配置对比对话框 -->
    <el-dialog
      v-model="compareDialogVisible"
      title="配置对比"
      width="95%"
      :before-close="handleCompareDialogClose"
    >
      <div v-if="compareConfigs.length === 0">
        <el-alert title="请选择两个配置进行对比" type="info" :closable="false" />
      </div>
      <div v-else-if="compareConfigs.length === 1">
        <el-alert :title="`已选择: ${compareConfigs[0].filename}，请选择第二个配置`" type="success" :closable="false" />
      </div>
      <div v-else>
        <el-descriptions :column="2" border style="margin-bottom: 20px;">
          <el-descriptions-item label="配置1">{{ compareConfigs[0].filename }}</el-descriptions-item>
          <el-descriptions-item label="配置2">{{ compareConfigs[1].filename }}</el-descriptions-item>
        </el-descriptions>
        
        <el-button type="primary" @click="performCompare" :loading="comparing" style="margin-bottom: 20px;">
          开始对比
        </el-button>
        <el-button @click="resetCompare">重置选择</el-button>
        
        <div v-if="diffResult" style="margin-top: 20px;">
          <el-alert v-if="!diffResult.has_changes" title="配置无变化" type="success" />
          <el-input
            v-else
            v-model="diffResult.diff"
            type="textarea"
            :rows="30"
            readonly
            style="font-family: 'Courier New', monospace; font-size: 12px; margin-top: 10px;"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { deviceApi, backupApi } from '@/api'
import { ElMessage, ElMessageBox } from 'element-plus'

const loading = ref(false)
const devices = ref([])
const selectedDevice = ref(null)
const configs = ref([])
const searchText = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const totalConfigs = ref(0)
const expandedRows = ref([])

// 对话框相关
const configDialogVisible = ref(false)
const selectedConfig = ref(null)
const configContent = ref('')
const compareDialogVisible = ref(false)
const compareConfigs = ref([])
const comparing = ref(false)
const diffResult = ref(null)

const filteredConfigs = computed(() => {
  let filtered = configs.value
  
  if (searchText.value) {
    const search = searchText.value.toLowerCase()
    filtered = filtered.filter(config => 
      config.filename.toLowerCase().includes(search) ||
      formatTime(config.backup_time).toLowerCase().includes(search)
    )
  }
  
  return filtered
})

const loadDevices = async () => {
  try {
    devices.value = await deviceApi.getDevices()
  } catch (error) {
    ElMessage.error('加载设备列表失败')
  }
}

const loadConfigHistory = async () => {
  if (!selectedDevice.value) {
    configs.value = []
    totalConfigs.value = 0
    return
  }

  loading.value = true
  try {
    const result = await backupApi.getBackups({ 
      device_id: selectedDevice.value,
      skip: (currentPage.value - 1) * pageSize.value,
      limit: pageSize.value
    })
    // 为每个配置添加预览相关属性
    configs.value = result.map(config => ({
      ...config,
      previewContent: '',
      previewLoading: false,
      previewLoaded: false
    }))
    totalConfigs.value = result.length
  } catch (error) {
    ElMessage.error('加载配置历史失败')
  } finally {
    loading.value = false
  }
}

const onDeviceChange = () => {
  currentPage.value = 1
  expandedRows.value = []
  loadConfigHistory()
}

const togglePreview = (row) => {
  const index = expandedRows.value.indexOf(row.id)
  if (index > -1) {
    expandedRows.value.splice(index, 1)
  } else {
    expandedRows.value.push(row.id)
  }
}

const loadPreviewContent = async (row) => {
  if (row.previewLoaded || row.previewLoading) return
  
  row.previewLoading = true
  try {
    const result = await backupApi.getBackupContent(row.id)
    row.previewContent = result.content
    row.previewLoaded = true
  } catch (error) {
    row.previewContent = '加载失败: ' + error.message
    row.previewLoaded = true
  } finally {
    row.previewLoading = false
  }
}

const viewConfig = async (config) => {
  selectedConfig.value = config
  configDialogVisible.value = true
  
  try {
    const result = await backupApi.getBackupContent(config.id)
    configContent.value = result.content
  } catch (error) {
    ElMessage.error('加载配置内容失败')
    configContent.value = '加载失败'
  }
}

const selectForCompare = (config) => {
  if (compareConfigs.value.length >= 2) {
    ElMessage.warning('最多只能选择两个配置进行对比')
    return
  }
  
  if (compareConfigs.value.find(c => c.id === config.id)) {
    ElMessage.warning('该配置已被选择')
    return
  }
  
  compareConfigs.value.push(config)
  compareDialogVisible.value = true
  
  if (compareConfigs.value.length === 1) {
    ElMessage.success('已选择第一个配置，请选择第二个配置')
  }
}

const performCompare = async () => {
  if (compareConfigs.value.length !== 2) {
    ElMessage.warning('请选择两个配置进行对比')
    return
  }
  
  comparing.value = true
  try {
    diffResult.value = await backupApi.compareBackups(
      compareConfigs.value[0].id,
      compareConfigs.value[1].id
    )
  } catch (error) {
    ElMessage.error('配置对比失败: ' + (error.response?.data?.detail || error.message))
  } finally {
    comparing.value = false
  }
}

const resetCompare = () => {
  compareConfigs.value = []
  diffResult.value = null
}

const deleteConfig = async (config) => {
  try {
    await ElMessageBox.confirm(
      `确定删除配置 "${config.filename}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await backupApi.deleteBackup(config.id)
    ElMessage.success('配置已删除')
    loadConfigHistory()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleConfigDialogClose = () => {
  configDialogVisible.value = false
  selectedConfig.value = null
  configContent.value = ''
}

const handleCompareDialogClose = () => {
  compareDialogVisible.value = false
  resetCompare()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  expandedRows.value = []
  loadConfigHistory()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  expandedRows.value = []
  loadConfigHistory()
}

const formatTime = (time) => {
  return new Date(time).toLocaleString('zh-CN')
}

const formatSize = (bytes) => {
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB'
  return (bytes / 1024 / 1024).toFixed(2) + ' MB'
}

const getStatusType = (status) => {
  return status === 'success' ? 'success' : status === 'failed' ? 'danger' : 'warning'
}

const getStatusText = (status) => {
  const map = { success: '成功', failed: '失败', in_progress: '进行中' }
  return map[status] || status
}

onMounted(() => {
  loadDevices()
})
</script>

<style scoped>
.config-history-page {
  max-width: 1400px;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: 500;
  font-size: 16px;
}

.config-viewer {
  max-height: 80vh;
  overflow-y: auto;
}

.config-preview {
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  margin: 10px 0;
}

.preview-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.preview-content {
  background-color: white;
  border-radius: 4px;
  padding: 10px;
  border: 1px solid #e4e7ed;
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-table__expand-icon) {
  color: #409eff;
}

:deep(.el-table__expand-icon--expanded) {
  color: #67c23a;
}

:deep(.el-textarea__inner) {
  resize: vertical;
  min-height: 200px;
}
</style>
